package com.bootdo.common.utils;

import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.UUID;

/**
 * 2017-06-11 19:12
 */
public class KeyUtil {

    /**
     * 生成唯一的主键
     * 格式: 时间+随机数
     * @return
     */
//    public static synchronized String genUniqueKey() {
//        Random random = new Random();
//        Integer number = random.nextInt(900000) + 100000;
//
//        return System.currentTimeMillis() + String.valueOf(number);
//    }

    private KeyUtil(){

    }

    private static KeyUtil keyUtil = null;

    public static KeyUtil getInstance(){
        if (keyUtil == null){
            synchronized (KeyUtil.class){
                if (keyUtil == null){
                    return keyUtil = new KeyUtil();
                }
            }
        }
        return keyUtil;
    }

    public  String genUniqueKey(){
        Random random = new Random();
        Integer number = random.nextInt(900000) + 100000;
        return System.currentTimeMillis() + String.valueOf(number);

    }


    public  String genUniqueKey64(){
        Random random = new Random();
        Integer number = random.nextInt(90000) + 10000;
        return String.valueOf(number);
    }


    /**
     * 20位末尾的数字id
     */
    public static volatile int Guid=100;

    public static String getGuid() {

        KeyUtil.Guid+=1;

        long now = System.currentTimeMillis();
        //获取4位年份数字
        SimpleDateFormat dateFormat=new SimpleDateFormat( DatetimeUtil.TIME_STAMP_PATTERN);
        //获取时间戳
        String time=dateFormat.format(now);
        String info=now+"";
        //获取三位随机数
        //int ran=(int) ((Math.random()*9+1)*100);
        //要是一段时间内的数据连过大会有重复的情况，所以做以下修改
        int ran=0;
        if(KeyUtil.Guid>999){
            KeyUtil.Guid=100;
        }
        ran= KeyUtil.Guid;

        return time+info.substring(2)+ran;
    }

    /**
     * 获取token
     * @return
     */
    public static String getToken() {
        return getGuid() + UUID.randomUUID().toString().replaceAll("-","");
    }


}

